# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    # 之前的，注释掉
    # '100127': {  # 致远支付  alipay-wap 50-10000 2.1% zs
    #     'API_KEY': 'b44f9f0952b3e852e55ccc67b364adef',
    #     'gateway': 'http://www.payzhiyuan.com/payapi/AlipayToCardGateWay.aspx',
    #     'query_gateway': '',
    # },
    # '100132': {  # 致远支付  alipay-wap 50-10000 2.1% witch
    #     'API_KEY': '8be7c3647cbb288cebadc3e6ac69af81',
    #     'gateway': 'http://www.payzhiyuan.com/payapi/AlipayToCardGateWay.aspx',
    #     'query_gateway': '',
    # },
    # '100131': {  # 致远支付  alipay-wap 50-10000 2.1% loki
    #     'API_KEY': '5d303f29594aa8c27c62690e314de4b0',
    #     'gateway': 'http://www.payzhiyuan.com/payapi/AlipayToCardGateWay.aspx',
    #     'query_gateway': '',
    # },
    # '100137': {  # 致远支付(鸿创)  alipay-wap 50-10000 2.1% dwc
    #     'API_KEY': '72d88e6fb228c423b6cd9dd2e1be0117',
    #     'gateway': 'http://www.payzhiyuan.com/payapi/AlipayToCardGateWay.aspx',
    #     'query_gateway': '',
    # },
    # '100141': {  # 致远支付(鑫源)  alipay-wap 50-10000 2.1% tt
    #     'API_KEY': '50713178b351fd57449f11e953bc3a89',
    #     'gateway': 'http://www.payzhiyuan.com/payapi/AlipayToCardGateWay.aspx',
    #     'query_gateway': '',
    # },
    # '100189': {  # 致远支付  alipay-wap 200-10000 2.1% sp
    #     'API_KEY': 'b03b34e547706a22d659b8fbaa463992',
    #     'gateway': 'http://www.payzhiyuan.com/payapi/AlipayToCardGateWay.aspx',
    #     'query_gateway': '',
    # },
    # '1660': {  # 致远支付  支付宝转银行卡 100——10000 1.4% witch
    #     'API_KEY': '689mZEKy6y8yHCRS3a85qR9oDCjr',
    #     'gateway': 'http://www.payzhiyuan.com/payapi/AlipayToCardGateWay.aspx',
    #     'query_gateway': '',
    # },
    '1972': {  # 致远支付  支付宝转银行卡 100——10000 1.4% witch
        'API_KEY': 'pfgpm5mY5Pwvs9tz9KMG5qA7cEaa',
        'gateway': 'http://service.jcn1893bc723.bajievippay.com/PayOrder/V3/',
        'query_gateway': 'http://service.jcn1893bc723.bajievippay.com/PayOrder/QueryPayOrderV3/',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s = s[:-1] + key
    _LOGGER.info("zhiyuanpay sign str: %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params['Sign']
    params.pop('Sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("zhiyuanpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'alipay_bank':
        return 11
    elif service == 'cloud_flash':
        return 13
    return 11


def _build_query_string(params):
    s = ''
    for k in params.keys():
        s += '%s=%s&' % (k, params[k])
    return s[:-1]


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('Amount', pay_amount),
        ('ChannelPlatform', _get_pay_type(service)),
        ('Ip', _get_device_ip(info)),
        ('MerchantId', app_id),
        ('MerchantUniqueOrderId', str(pay.id)),
        ('NotifyUrl', '{}/pay/api/{}/zhiyuanpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('ReturnUrl', '{}/pay/api/{}/zhiyuanpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('Timestamp', local_now().strftime('%Y%m%d%H%M%S')),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("zhiyuanpay create: %s, order_id is:%s ", json.dumps(parameter_dict), parameter_dict['MerchantUniqueOrderId'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('zhiyuanpay create response: %s:', response.text)
    return {'charge_info': json.loads(response.text)['Url']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zhiyuanpay notify data: %s, order_id is: %s", data, data['MerchantUniqueOrderId'])
    verify_notify_sign(data, api_key)
    pay_id = data['MerchantUniqueOrderId']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('zhiyuanpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = '1'
    trade_no = data['MerchantUniqueOrderId']
    total_fee = float(data['Amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1' and total_fee > 0.0:
        _LOGGER.info('zhiyuanpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('MerchantId', app_id),
        ('MerchantUniqueOrderId', pay_id),
        ('Timestamp', local_now().strftime('%Y%m%d%H%M%S')),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("zhiyuanpay query data: %s, order_id: %s", json.dumps(parameter_dict),
                 parameter_dict['MerchantUniqueOrderId'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("zhiyuanpay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['PayOrderStatus'])
        trade_no = pay_order.third_id
        total_fee = float(pay_order.total_fee)
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == '100':
            _LOGGER.info('zhiyuanpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('zhiyuanpay data error, status_code: %s', response.status_code)

